"""
日志工具模块
"""
import time
import os
from typing import Optional


class Logger:
    """统一的日志记录器"""
    
    def __init__(self, log_dir: str = "logs"):
        self.log_dir = log_dir
        os.makedirs(log_dir, exist_ok=True)
    
    def _get_timestamp(self) -> str:
        """获取当前时间戳"""
        return time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime())
    
    def _format_name(self, first_name: str, last_name: str) -> str:
        """格式化姓名为"姓_名"格式"""
        return f"{last_name}_{first_name}"
    
    def _write_to_file(self, message: str, filename: str):
        """写入日志文件"""
        # 如果filename包含下划线，说明已经是"姓_名"格式，直接使用
        # 否则使用原格式
        if '_' in filename and filename != 'system':
            log_file = os.path.join(self.log_dir, f"logs-{filename}")
        else:
            log_file = os.path.join(self.log_dir, f"logs-{filename}")
        
        with open(log_file, 'a', encoding='utf-8') as f:
            f.write(f'[{self._get_timestamp()}] - {message}\n')
    
    def log(self, message: str, name: str = 'system'):
        """记录日志并打印到控制台"""
        timestamp = self._get_timestamp()
        formatted_message = f'[{timestamp}] - {message}'
        
        # 打印到控制台
        print(formatted_message)
        
        # 写入个人日志文件
        self._write_to_file(message, name)
        
        # 如果不是系统日志，同时写入系统日志
        if name != 'system':
            self._write_to_file(message, 'system')
    
    def log_user(self, message: str, first_name: str, last_name: str):
        """记录用户日志，使用"姓_名"格式"""
        formatted_name = self._format_name(first_name, last_name)
        timestamp = self._get_timestamp()
        formatted_message = f'[{timestamp}] - {message}'
        
        # 打印到控制台
        print(formatted_message)
        
        # 写入用户个人日志文件
        self._write_to_file(message, formatted_name)
        
        # 同时写入系统日志
        self._write_to_file(message, 'system')


# 全局日志实例
logger = Logger()
